package com.fsoft.core.common.base.contorller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fsoft.core.common.base.entity.UploadFileVo;
import com.fsoft.core.excel.entity.ExcelModel;
import com.fsoft.core.excel.service.ExcelService;
import com.fsoft.core.utils.OgnlUtils;
import com.fsoft.core.utils.RetVo;

@Controller
@RequestMapping("/common")
public class CommonController extends BaseController {

	@Autowired
	private ExcelService excelService;

	@ResponseBody
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public RetVo commonUpload(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			List<UploadFileVo> ret = super.commonsUploadEx(params, request, response);
			if (OgnlUtils.isNotEmpty(ret))
				return RetVo.ok(ret.size(), ret.get(0));
			return RetVo.error("上传失败，文件数量= 0");
		} catch (Exception e) {
			return RetVo.error(e.getMessage());
		}
	}

	@ResponseBody
	@PostMapping(value = "/export")
	public RetVo export(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String jsonModel = params.get("model").toString();
		jsonModel = jsonModel.replaceFirst("\"", "");
		jsonModel = jsonModel.substring(0, jsonModel.length() - 1);
		ExcelModel model = JSON.parseObject(jsonModel, ExcelModel.class);

		if (OgnlUtils.isNotEmpty(model.getModelPath()) && !StringUtils.equals(model.getModelPath(), "ModelDefined")) {
			// 指定模板
			excelService.executeExport(model, request, response);
		} else {
			// 默认模板
			excelService.executeExportDef(model, request, response);
		}
		return RetVo.ok();
	}
}
